<script lang="ts" setup>
import { type FormInstance, Message } from '@arco-design/web-vue'
import { useForm } from '@/hooks'
import { copyFields } from '@/utils/tools'
import { CouponApi, ParentApi, StudentApi } from '@/apis'
import { Regexp } from '@/utils'

interface Props {
  data?: ParentApi.ParentResp
  studentId: string | undefined
  // readonly?: boolean
}

const props = defineProps<Props>()

const emits = defineEmits(['change'])

const isExpand = ref<boolean>(false)
const readonly = ref<boolean>(true)
const { form } = useForm<ParentApi.ParentResp>({
  id: '',
  name: '',
  mobilePhone: '',
  recommender: '',
  username: '',
  status: '',
  parentRemark: '',
  createTime: '',
  studentList: [],
})

const rules: FormInstance['rules'] = {
  mobilePhone: [{ required: false, match: Regexp.Phone, message: '请输入正确的手机号码' }],
  recommender: [{ required: false, match: Regexp.Phone, message: '请输入正确的手机号码' }],
}

const couponList = ref<CouponApi.CouponDetail[]>([])

const getCoupon = async (id: string) => {
  // const res = await CouponApi.getParentCoupon(id)
  const res = await CouponApi.getParentCouponList({ parentId: id })
  couponList.value = res
}

watch(() => props.data, (val: ParentApi.ParentResp) => {
  copyFields(val, form)
  getCoupon(form.id)
})

const loading = ref(false)

const onEdit = () => {
  readonly.value = false
}

const onCancel = () => {
  readonly.value = true
  for (const key in form) {
    form[key] = props.data?.[key]
  }
  getCoupon(form.id)
}

const onSave = async () => {
  try {
    await StudentApi.updateParent(form, props.studentId)
    if (form.recommender && !props.data?.recommender) {
      await StudentApi.setRecommender(form.id, { recommenderPhone: form.recommender })
    }
    Message.success('修改成功')
    emits('change')
    readonly.value = true
    // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) { }
}

const commit = async (data: any) => {
  loading.value = true
  try {
    await ParentApi.updateParent(data, `${props.data?.id}`)
    return true
    // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {
    return false
  } finally {
    loading.value = false
  }
}

const pwdData = ref({
  pwd: '',
  ppwd: '',
})
const pwdRules: FormInstance['rules'] = {
  pwd: [{ required: true, message: '请输入新密码' }],
  ppwd: [{ required: true, message: '请再次输入新密码' }],
}
const pwdRef = ref<FormInstance>()
const visible = ref<boolean>(false)
const handleCancel = () => {
  visible.value = false
}

// 修改密码
const reset = () => {
  pwdData.value.pwd = ''
  pwdData.value.ppwd = ''
  pwdRef.value?.resetFields()
}

const beforeOk = async () => {
  const vali = await pwdRef.value?.validate()
  if (vali) {
    return false
  }
  if (pwdData.value.ppwd !== pwdData.value.pwd) {
    Message.warning('两次密码不一致！')
    return false
  } else {
    const res = await commit({ password: pwdData.value.pwd, name: form.name, mobilePhone: form.mobilePhone, status: form.status })
    if (res) {
      Message.success('修改成功')
    }
    return res
  }
}

const open = () => {
  reset()
  visible.value = true
}
</script>

<template>
  <div v-if="props.data" class="parent-info">
    <div class="head">
      <h2>
        {{ form.name ?? '--' }}
        <icon-edit :size="16" class="btn" @click="onEdit" />
      </h2>
      <a-space>
        <a-avatar :size="24" :style="{ backgroundColor: '#55b96d' }">
          <icon-wechat />
        </a-avatar>
        <a-avatar :size="24" :style="{ backgroundColor: '#3370ff' }">
          <icon-twitter-circle-fill />
        </a-avatar>
        <a-avatar :size="24">
          A
        </a-avatar>
        <a-avatar :size="24">
          B
        </a-avatar>
      </a-space>
    </div>
    <a-divider />
    <div class="detail">
      <h3>家长信息</h3>
      <a-form :model="form" :rules="rules" :readonly style="padding: 0 15px;">
        <readonly-form-item label="姓名" label-col-flex="70px" :span="24" field="name">
          <template #label>
            <div class="label">
              姓名
            </div>
          </template>
          <a-input v-model.trim="form.name" label-col-flex="70px" placeholder="请输入姓名" :max-length="32" />
        </readonly-form-item>
        <readonly-form-item label="电话" label-col-flex="70px" :span="24" field="mobilePhone">
          <template #label>
            <div class="label">
              电话
            </div>
          </template>
          <a-input v-model.trim="form.mobilePhone" placeholder="请输入电话" :max-length="11" />
        </readonly-form-item>
        <readonly-form-item label="用户名" label-col-flex="70px" :span="24" field="username">
          <template #label>
            <div class="label">
              用户名
            </div>
          </template>
          <a-input v-model.trim="form.username" placeholder="请输入用户名" :max-length="11" disabled />
        </readonly-form-item>
        <readonly-form-item label="推荐人" label-col-flex="70px" :span="24" field="recommender">
          <template #label>
            <div class="label">
              推荐人
            </div>
          </template>
          <a-input
            v-model.trim="form.recommender" placeholder="请输入推荐人" :max-length="11"
            :disabled="data?.recommender ? true : false"
          />
        </readonly-form-item>
        <readonly-form-item label="加入时间" label-col-flex="70px" :span="24" field="createTime">
          <template #label>
            <div class="label">
              加入时间
            </div>
          </template>
          <span>{{ form.createTime }}</span>
        </readonly-form-item>
        <!-- <readonly-form-item label="上次登陆时间" label-col-flex="70px" :span="24" field="lastLoginTime">
          <template #label>
            <div class="label">
              上次登陆时间
            </div>
          </template>
          <span>{{ form.lastLoginTime || '-' }}</span>
        </readonly-form-item> -->
        <readonly-form-item label="账号状态" label-col-flex="70px" :span="24" field="status">
          <template #label>
            <div class="label">
              账号状态
            </div>
          </template>
          <template #readonly>
            <a-space>
              <span class="status" :class="`status${form.status}`">{{ `${form.status}` === '0' ? '禁用' : '启用' }}</span>
              <a-link status="danger" size="small" @click="open">
                重置密码
              </a-link>
            </a-space>
          </template>
          <a-space>
            <span class="status" :class="`status${form.status}`">{{ `${form.status}` === '0' ? '有效' : '禁用' }}</span>
            <a-link status="danger" size="small" @click="open">
              重置密码
            </a-link>
          </a-space>
        </readonly-form-item>
        <readonly-form-item label="未使用优惠数" label-col-flex="70px" :span="24" field="name">
          <template #label>
            <div class="label">
              未使用优惠数
            </div>
          </template>
          <template #readonly>
            <div>
              <span class="count">{{ couponList.length }}张</span>
              <a-link v-if="couponList.length" size="small" @click="isExpand = !isExpand">
                {{ isExpand ? '隐藏' : '查看' }}
              </a-link>
            </div>
          </template>
          <div>
            <span class="count">{{ couponList.length }}张</span>
            <a-link v-if="couponList.length" size="small" @click="isExpand = !isExpand">
              {{ isExpand ? '隐藏' : '查看' }}
            </a-link>
          </div>
        </readonly-form-item>
      </a-form>
      <div v-show="isExpand" class="coupons">
        <div v-for="(item, index) in couponList" :key="index" class="item">
          <a-image :width="36" :height="36" :src="item.image" :preview="false" />
          <div class="desc">
            <div class="name">
              {{ item.name }}
            </div>
            <div>有效天数：{{ item.validDays }}</div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="!readonly" class="foot">
      <a-button class="btn" @click="onCancel">
        取消
      </a-button>
      <a-button class="btn" type="primary" @click="onSave">
        保存
      </a-button>
    </div>
  </div>
  <a-modal v-model:visible="visible" title="重置密码" width="300px" :on-before-ok="beforeOk" @cancel="handleCancel">
    <a-form ref="pwdRef" layout="vertical" :rules="pwdRules" :model="pwdData" :auto-label-width="true">
      <a-form-item label="新密码" field="pwd">
        <a-input v-model.trim="pwdData.pwd" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item label="确认密码" field="ppwd">
        <a-input v-model.trim="pwdData.ppwd" placeholder="请再次输入新密码" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style lang="less" scoped>
.parent-info {
  .head {
    padding: 0 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  h2,
  h3 {
    color: #111;
    padding: 0 15px;
  }

  .detail {
    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .btn {
      cursor: pointer;
    }

    :deep(.arco-input-wrapper) {
      background-color: #fff;
    }
  }

  .foot {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;

    .btn {
      width: 40%;
    }
  }

  .coupons {
    max-height: 500px;
    overflow-y: auto;
    padding: 0 15px;
    padding-bottom: 15px;

    .item {
      border-radius: 4px;
      padding: 8px 10px;
      background: #fff;
      display: flex;
      align-items: center;

      &:not(:first-child) {
        margin-top: 8px;
      }

      .desc {
        font-size: 13px;
        margin-left: 10px;
        line-height: 18px;
        color: #888;

        .name {
          color: #111;
        }
      }
    }
  }

  .label {
    flex-shrink: 0;
    width: 90px;
    text-align: left;
    color: #999;
  }

  :deep(.arco-form-item) {
    margin-bottom: 0px;
  }

  :deep(.arco-card-header),
  :deep(.arco-card-body) {
    padding: 0;
  }

  .status {
    font-size: 14px;
    padding-left: 10px;
    position: relative;

    &::before {
      position: absolute;
      content: '';
      width: 6px;
      height: 6px;

      border-radius: 50%;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .status0 {
    color: #00b42a;

    &::before {
      background: #00b42a;
    }
  }

  .status1 {
    color: #999;

    &::before {
      background: #999;
    }
  }

  .count {
    color: #165dff;
    font-size: 14px;
    margin-right: 24px;
  }
}
</style>
